package com.hama.iotrust.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class StrUtil {

    private static final Logger logger = LoggerFactory.getLogger(StrUtil.class);

    // public static String jsonFromObject(Object object) {
    // StringWriter writer = new StringWriter();
    // try {
    // ObjectMapper mapper = new ObjectMapper();
    // mapper.setSerializationInclusion(Inclusion.NON_NULL);
    // mapper.writeValue(writer, object);
    // } catch (Exception e) {
    // logger.error("Unable to serialize to json: " + object, e);
    // return null;
    // }
    // return writer.toString();
    // }

    public static String jsonFromObject(Object object) {
        SerializerFeature[] features = new SerializerFeature[] { SerializerFeature.WriteMapNullValue,
                            SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty,
                            SerializerFeature.QuoteFieldNames, SerializerFeature.WriteDateUseDateFormat,
                            SerializerFeature.PrettyFormat, SerializerFeature.WriteEnumUsingToString,
                            SerializerFeature.DisableCircularReferenceDetect };
        return JSON.toJSONString(object, features);
    }

    /**
     * MD5 加密
     *
     * @param str
     * @return
     */
    public static String getMD5Str(String str) {
        MessageDigest messageDigest = null;

        try {
            messageDigest = MessageDigest.getInstance("MD5");

            messageDigest.reset();

            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            logger.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }

        byte[] byteArray = messageDigest.digest();

        StringBuffer md5StrBuff = new StringBuffer();

        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }

        return md5StrBuff.toString();
    }

    /**
     * 十六进制转字符串
     *
     * @param b
     * @return
     */
    public static String byte2hex(byte[] b) {
        StringBuffer hs = new StringBuffer();
        String stmp = "";
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) hs.append("0" + stmp);
            else hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }

    //字节数组转化为有空格的字节字符串
    public static String byte2hexWithSpace(byte[] b) {
        StringBuffer hs = new StringBuffer();
        String stmp = "";
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) hs.append("0" + stmp);
            else hs.append(stmp);
            if (n != b.length - 1) hs.append(" ");
        }
        return hs.toString().toUpperCase();
    }

    /**
     * 字节转化为二进制字符串
     */
    public static String byteToBinary(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE);
        for (int i = 0; i < Byte.SIZE * bytes.length; i++)
            sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
        return sb.toString();
    }

    public static int byteToInt(byte intByte) {
        int n = intByte & 0xFF;
        return n;
    }

    public static int bytesToInt(byte[] intByte, int byteLength) {
        int fromByte = 0;
        for (int i = 0; i < byteLength; i++) {
            int n = (intByte[i] & 0xff) << (8 * (byteLength - 1 - i));
            fromByte += n;
        }
        return fromByte;
    }

    public static String byteToBin(byte binary, int bitLength) {
        String binStr = Integer.toBinaryString(byteToInt(binary));
        if (binStr.length() < bitLength) {
            StringBuilder formatted = new StringBuilder();
            formatted.append(binStr);
            do {
                formatted.insert(0, "0");
            } while (formatted.length() < bitLength);
            return formatted.toString();
        }
        return binStr;
    }

    /**
     * 四舍五入 保留两位小数
     */
    public static double doubleToTwoDecimal(double f) {
        BigDecimal bg = new BigDecimal(f);
        double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return f1;
    }

    /**
     * 是否为空白,包括null和""
     */
    public static boolean isEmpty(Object str) {
      return str == null || str.toString().length() == 0;
    }

    /**
     * 16进制字符串转化为字节数组
     *
     */

    public static byte[] hex2byte(String str) { 
        if (str == null)
         return null;
        str = str.trim();
        int len = str.length();
        if (len == 0 || len % 2 == 1)
         return null;

        byte[] b = new byte[len / 2];
        try {
         for (int i = 0; i < str.length(); i += 2) {
          b[i / 2] = (byte) Integer
            .decode("0x" + str.substring(i, i + 2)).intValue();
         }
         return b;
        } catch (Exception e) {
         return null;
        }
     }
    
    
    /**
     * 10进制数转化为4位的2进制数
     * @param i
     * @return
     */
    public static String intToBin(int i){
    	String binStr = Integer.toBinaryString(i);
    	if(binStr.length()<4){
    		do {
				binStr = "0"+binStr; 
			} while (binStr.length()<4);
    	}
    	return binStr;
    }

    /**
	 * map按value排序
	 * @param map
	 * @return list
	 * @author rongqiang
	 */
	public static ArrayList<Map.Entry<Long, Long>> getSortedHashtableByValue(Map<Long,Long> map){
		ArrayList<Map.Entry<Long, Long>> list = new ArrayList<Map.Entry<Long,Long>>(map.entrySet());
		Collections.sort(list,new Comparator<Map.Entry<Long, Long>>() {
			public int compare(Map.Entry<Long, Long> m1, Map.Entry<Long,Long> m2){
				return (int) (m2.getValue() - m1.getValue());
			}
		});
		return list;
	}
	
	/**
	 * 产生一个6位的随机验证码，用于手机验证。
	 * 
	 * @author liyang
	 */
	public static String Verification() {
		String str = "";
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			str += random.nextInt(10) + "";
		}
		return str;
	}

    public static String join(Collection col,String str){
        StringBuilder sb = new StringBuilder(str);
        for (Object o:col){
            sb.append(str).append(o);
        }
        sb.deleteCharAt(0);
        return sb.toString();
    }
}
